function roleChanged() {
    var ele = document.getElementById("role");
    var role = ele.value;
    ele.style = "";
    if(role == 1 || role == 2) { // 供应商 或 子账号
        document.getElementById("code").readOnly = false;
        document.getElementById("account").readOnly = false;
        document.getElementById("business").readOnly = true;
        document.getElementById("warehouseId").readOnly = true;
        document.getElementById("password").readOnly = false;
        document.getElementById("verifyCode").readOnly = false;
        document.getElementById("accountDiv").style.display = "";
        document.getElementById("businessDiv").style.display = "none";
        document.getElementById("warehouseDiv").style.display = "none";
    } else if(role == 3) { // 承运商
        document.getElementById("code").readOnly = false;
        document.getElementById("account").readOnly = true;
        document.getElementById("business").readOnly = false;
        document.getElementById("warehouseId").readOnly = true;
        document.getElementById("password").readOnly = false;
        document.getElementById("verifyCode").readOnly = false;
        document.getElementById("accountDiv").style.display = "none";
        document.getElementById("businessDiv").style.display = "";
        document.getElementById("warehouseDiv").style.display = "none";
    } else if(role == 4 || role == 5) { // 当当管理员业务员
        document.getElementById("code").readOnly = false;
        document.getElementById("account").readOnly = true;
        document.getElementById("business").readOnly = true;
        document.getElementById("warehouseId").readOnly = false;
        document.getElementById("password").readOnly = false;
        document.getElementById("verifyCode").readOnly = false;
        document.getElementById("accountDiv").style.display = "none";
        document.getElementById("businessDiv").style.display = "none";
        document.getElementById("warehouseDiv").style.display = "";
        queryWarehouses();
    } else {
        document.getElementById("code").readOnly = true;
        document.getElementById("account").readOnly = true;
        document.getElementById("business").readOnly = true;
        document.getElementById("warehouseId").readOnly = true;
        document.getElementById("password").readOnly = true;
        document.getElementById("verifyCode").readOnly = true;
        document.getElementById("accountDiv").style.display = "";
        document.getElementById("businessDiv").style.display = "none";
        document.getElementById("warehouseDiv").style.display = "none";
    }
}

function queryWarehouses() {
    $.ajax({
        type: "GET",
        url: "/base/warehouses",
        async: false,
        data: {},
        success: function(result){
            if(result.status == 200){
                resetWarehouses(result.data);
            } else {
                alert(result.message);
            }
        },
        error: function(xmlHttpRequest, textStatus, errorThrown){
            var errmsg = "请求失败: status=" + xmlHttpRequest.status + ", readyState=" + xmlHttpRequest.readyState
                + ", text=" + textStatus;
            alert(errmsg);
        }
    });
}

var warehouses = new Array();
function resetWarehouses(data) {
    warehouses = data;
    var select = document.getElementById("warehouseId");
    var options = select.options;
    options.length = 1;
    for(var i=0; i<data.length; i++){
        var item = data[i];
        var option = new Option(item.name, item.id);
        options.add(option);
    }
}

function applyWarehouseType() {
    var warehouseTypeEle = document.getElementById("warehouseType");
    warehouseTypeEle.value = "";
    var warehouseIdEle = document.getElementById("warehouseId");
    var warehouseId = warehouseIdEle.value;
    warehouseIdEle.style = "";
    if(!warehouseId) {
        return;
    }
    for(var i=0; i<warehouses.length; i++) {
        var w = warehouses[i];
        if(w.id == warehouseId) {
            warehouseTypeEle.value = w.type;
            return;
        }
    }
    alert("warehouse type fail");
}

function checkRoleInput() {
    var roleValue = document.getElementById("role").value;
    if(!roleValue) {
        alert("请先选择角色，再输入单位注册码");
    }
}

function login() {
    var loginDiv = document.getElementById("loginDiv");
    var clickFunction = loginDiv.onclick;
    loginDiv.onclick = null;
    loginDiv.innerText = "登录中...";
    applyVerifyCode();
    var data = $("#loginForm").serialize();
    $.ajax({
        type: "POST",
        url: "/dangdangOs/loginApi",
        async: true,
        data: data,
        success: function(result){
            console.log($("#code").val())
            console.log(result)
            if(result.status == 200){
                if(window.location.search) {
                    const urlParams = new URLSearchParams(window.location.search)
                    const by = decodeURIComponent(urlParams.get('by'));
                    const to = decodeURIComponent(urlParams.get('from'))
                    const isbn = urlParams.get('isbn')
                    const serialNo = urlParams.get('serialNo')
                    window.location.href = `${to}?username=${$("#code").val()}&phpsessid=${result.phpsessid}&by=${by}&isbn=${isbn}&serialNo=${serialNo}`
                }
                // var redirectUrl = document.getElementById("url").value;
                // if(redirectUrl) {
                //     window.location = "/index?url=" + redirectUrl;
                // } else {
                //     window.location = "/index";
                // }
            } else if(result.status == 203){
				document.getElementById("smsValidateMask").style.display = "block";
				document.getElementById("smsValidateModel").style.display = "block";
				var data = result.data;
				document.getElementById("vrmHex").value = data.hex;
				document.getElementById("vrmId").value = data.vrmId;
				loginDiv.onclick = clickFunction;
				loginDiv.innerText = "登录";
			} else {
                errorInfo(result);
                refreshVerifyImg();
                loginDiv.onclick = clickFunction;
                loginDiv.innerText = "登录";
            }
        },
        error: function(xmlHttpRequest, textStatus, errorThrown){
            var errmsg = "请求失败: status=" + xmlHttpRequest.status + ", readyState=" + xmlHttpRequest.readyState
                + ", text=" + textStatus;
            alert(errmsg);
            loginDiv.onclick = clickFunction;
            loginDiv.innerText = "登录";
        }
    });
}

function showDelIcon(id) {
    document.getElementById(id).style.display = "block";
}

function clearError(ele) {
    ele.style.color = "#333333";
    ele.style.borderColor = "#cccccc";
}

function clearContent(id, el) {
    var ele = document.getElementById(id);
    ele.value = "";
	el.style.display = "none";
}

// var errstyle = "color: #d11010;border-color: #d11010;";
function errorInfo(result) {
    try {
        var status = result.status;
        var message = result.message;
        clearErrorStyle("role");
        clearErrorStyle("code");
        clearErrorStyle("account");
        clearErrorStyle("business");
        clearErrorStyle("warehouseId");
        clearErrorStyle("password");
        document.getElementById("verifyErrDiv").style.display = "none";
        switch (status) {
            case 401:
                showErrorStyle("role");
                break;
            case 402:
                showErrorStyle("code");
                break;
            case 403:
                showErrorStyle("business");
                break;
            case 405:
                showErrorStyle("warehouseId");
                break;
            case 406:
                showErrorStyle("password");
                break;
            case 407:
                var errDiv = document.getElementById("verifyErrDiv");
                errDiv.innerText = message;
                errDiv.style.display = "block";
                break;
            // case 408:
            //     alert("未知的用户");
            //     break;
        }
    } catch (e) {
        printException(e);
    } finally {
        alert(message);
    }
}

function printException(e) {
    try {
        console.info("script error: " + e.name + ", " + e.message);
    } catch (e2) {
    }
}

function showErrorStyle(id) {
    var ele = document.getElementById(id);
    ele.style.color = "#d11010";
    ele.style.borderColor = "#d11010";
}

function clearErrorStyle(id) {
    var ele = document.getElementById(id);
    ele.style.color = "#333333";
    ele.style.borderColor = "#cccccc";
}

function toRegisterPage() {
    window.location = "/base/carrier/toRegister";
}

function showModal() {
    document.getElementById("mask").style.display = "block";
    document.getElementById("modal").style.display = "block";
}

function closeModal() {
    document.getElementById("mask").style.display = "none";
    document.getElementById("modal").style.display = "none";
}

function closeValidateModel() {
	document.getElementById("smsValidateMask").style.display = "none";
	document.getElementById("smsValidateModel").style.display = "none";
	document.getElementById("recordPhone").value = "";
	document.getElementById("smsCode").value = "";
	document.getElementById("recordFlag").className="";
	hideRecordPhoneError();
	refreshVerifyImg();
}

function showRecordPhoneError(showText){
	showErrorStyle("recordPhone");
	document.getElementById("recordPhoneErr").style.display = "block";
	document.getElementById("recordPhoneErrSpan").innerHTML = showText;
}

function hideRecordPhoneError(){
	clearErrorStyle("recordPhone");
	document.getElementById("recordPhoneErr").style.display = "none";
	document.getElementById("recordPhoneErrSpan").innerHTML ="";
}

function checkRecordPhone(){
	var phone = document.getElementById("recordPhone").value;
	hideRecordPhoneError();
	document.getElementById("validPhone").value= "";
	document.getElementById("recordFlag").className="";
	var vrmId = document.getElementById("vrmId").value;
	if(isNull(phone)){
		showRecordPhoneError("请输入备案手机号");
		return;
	}
	if(!isMobileNumber(phone)){
		showRecordPhoneError("输入的备案手机号格式错误");
		return;
	}
	$.ajax({
		type:"POST",
		url:"/base/checkRecordPhone",
		dataType: 'json',
		data: {"phone":phone,"vrmId":vrmId},
		success: function(result){
			if(result.status == 200){
				// if(result.data  )
				document.getElementById("validPhone").value=1;
				document.getElementById("recordFlag").className = "correct";
				$("#smsCodeSend").attr("disabled", "disabled");
				getValidateCode();
			}else{
				//todo
				showRecordPhoneError(result.message);
				// document.getElementById("recordFlag").className = "incorrect";
			}
		},
		error: function(xmlHttpRequest, textStatus, errorThrown){
			var errmsg = "请求失败: status=" + xmlHttpRequest.status + ", readyState=" + xmlHttpRequest.readyState
				+ ", text=" + textStatus;
			alert(errmsg);
		}
	});
}

function isMobileNumber(str) {
	var g = /^1[3456789]\d{9}$/;
	return g.test(str);
}

function isNull(str){
	if(str == "" || str == null || str == undefined){
		return true;
	}else{
		return false;
	}
}
function checkSmsCode(){
	hideRecordPhoneError();
	var phone = document.getElementById("recordPhone").value;
	if(isNull(phone)){
		showRecordPhoneError("请输入备案手机号");
		return;
	}
	if(!isMobileNumber(phone)){
		showRecordPhoneError("输入的备案手机号格式错误");
		return;
	}
	var code = document.getElementById("smsCode").value;
	if(isNull(code)){
		showRecordPhoneError("请输入验证码");
		return;
	}
	var validPhone = document.getElementById("validPhone").value;
	if(validPhone != 1){
		alert("请先检查手机号并获取验证码");
		return;
	}
	var vrmHex = document.getElementById("vrmHex").value;
	var vrmId = document.getElementById("vrmId").value;
	var data = {'phone':phone, 'smsCode':code, "vrmHex":vrmHex, "vrmId":vrmId};
	$.ajax({
		type: "POST",
		url: "/base/checkSmsCode",
		dataType: 'json',
		data: data,
		success: function(result){
			if(result.status == 200){
				var redirectUrl = document.getElementById("url").value;
				if(redirectUrl) {
					window.location = "/index?url=" + redirectUrl;
				} else {
					window.location = "/index";
				}
			}else{
				alert(result.message);
			}
		},
		error: function(xmlHttpRequest, textStatus, errorThrown){
			var errmsg = "请求失败: status=" + xmlHttpRequest.status + ", readyState=" + xmlHttpRequest.readyState
				+ ", text=" + textStatus;
			alert(errmsg);
		}
	});
}

function getValidateCode(){
	var phone = document.getElementById("recordPhone").value;
	var vrmId = document.getElementById("vrmId").value;
	if(isNull(phone)){
		showRecordPhoneError("请输入备案手机号");
		return;
	}
	if(!isMobileNumber(phone)){
		showRecordPhoneError("输入的备案手机号格式错误");
		return;
	}

	$.ajax({
		type: "POST",
		url: "/base/sendSmsCode",
		dataType: 'json',
		data: {"phone": phone,"vrmId":vrmId},
		success: function(result){
			if(result.status == 200){
				console.log(result);
			}else{
				alert(result.message);
			}
		},
		error: function(xmlHttpRequest, textStatus, errorThrown){
			var errmsg = "请求失败: status=" + xmlHttpRequest.status + ", readyState=" + xmlHttpRequest.readyState
				+ ", text=" + textStatus;
			alert(errmsg);
		}
	});

	var code = $("#smsCodeSend");
	code.attr("disabled", "disabled");
	setTimeout(function(){
		code.css("opacity", "0.8");
	}, 1000);
	var time = 120;
	var set = setInterval(function(){
		code.val("(" + --time + ")秒后重新获取");
	}, 1000);
	setTimeout(function(){
		code.attr("disabled", false).val("重新获取验证码");
		clearInterval(set);
	}, 120000);
}